﻿using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System;
using System.IO.Ports;

namespace comtool
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        string selected_port;
        UInt32 buadrate;
        SerialPort serial;

        UInt16 state;

        public MainWindow()
        {
            InitializeComponent();

            string[] serial_list = System.IO.Ports.SerialPort.GetPortNames();
            for (int i = 0; i < serial_list.Length; i++)
            {
                this.serial_select.Items.Add(serial_list[i]);
            }
            
            buadrate = Convert.ToUInt32(this.serial_baudrate.Text, 10);
            selected_port = serial_select.Text;
            serial = new SerialPort();
            // serial.PortName = selected_port;
            serial.BaudRate = Convert.ToInt32(buadrate);
            serial.Parity = Parity.None;
            serial.StopBits = StopBits.One;
            serial.DataBits = 8;
            serial.Handshake = Handshake.None;

            state = 0;
        }

        private void serial_scan_Click(object sender, RoutedEventArgs e)
        {
            this.serial_select.Items.Clear();
            string[] serial_list = System.IO.Ports.SerialPort.GetPortNames();
            for (int i = 0; i < serial_list.Length; i++)
            {
                this.serial_select.Items.Add(serial_list[i]);
            }
        }

        private void serial_select_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            selected_port = serial_select.Text;
        }

        private void serial_open_close_Click(object sender, RoutedEventArgs e)
        {
            if(state == 0)
            {
                serial.PortName = this.serial_select.Text;
                serial.BaudRate = Convert.ToInt32(this.serial_baudrate.Text, 10);
                serial.Open();

                this.serial_open_close.Content = "关闭";

                state = 1;
            }
            else
            {
                this.serial_open_close.Content = "打开";
                serial.Close();
                state = 0;
            }

        }

        private void serial_baudrate_TextChanged(object sender, TextChangedEventArgs e)
        {
            buadrate = Convert.ToUInt32(this.serial_baudrate.Text, 10);
        }
    }
}